<template>
  <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
    <div class="resumes">
      <!-- 操作区域 -->
      <a-space direction="horizontal" :size="16" style="margin-bottom: 16px;">
        <a-input-search
            v-model:value="searchKeyword"
            placeholder="搜索简历标题"
            enter-button="搜索"
            @search="handleSearch"
        />
        <a-button type="primary" @click="showModal()">
          新增简历
        </a-button>
      </a-space>

      <!-- 表格区域 -->
      <a-table
          :columns="columns"
          :row-key="record => record.resumeId"
          :data-source="resumes"
          :pagination="pagination"
          :loading="isLoading"
          @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <!-- 用户名列格式化 -->
          <template v-if="column.dataIndex === 'userId'">
            {{ getUserDisplayName(record.userId) }}
          </template>

          <!-- 简历内容列格式化 -->
          <template v-if="column.dataIndex === 'resumeContent'">
            {{ record.resumeContent }}
          </template>

          <!-- 创建时间格式化 -->
          <template v-if="column.dataIndex === 'createdAt'">
            {{ formatDate(record.createdAt) }}
          </template>
          <template v-if="column.dataIndex === 'isDefault'">
            {{ record.isDefault === 1 ? '是' : '否' }}
          </template>

          <!-- 操作列 -->
          <template v-if="column.dataIndex === 'action'">
            <a-space size="small">
              <a-button type="primary" @click="showModal(record)">编辑</a-button>
              <a-popconfirm
                  title="是否确认删除该简历？"
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="deleteResume(record)"
              >
                <a-button danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
  </a-layout-content>

  <!-- 编辑/新增模态框 -->
  <a-modal
      v-model:open="open"
      :title="selectedResume.resumeId ? '编辑简历' : '新增简历'"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      :bodyStyle="{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }"
  >
    <!-- 用户名下拉列表 -->
    <a-form-item label="用户名" style="width: 100%; padding-left: 50px">
      <a-select v-model:value="selectedResume.userId" style="width: 100%">
        <a-select-option v-for="user in users" :key="user.userId" :value="user.userId">
          {{ user.username }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form ref="formRef" :model="selectedResume" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" style="width: 100%;">
      <a-form-item label="简历标题">
        <a-input v-model:value="selectedResume.resumeTitle" />
      </a-form-item>
      <a-form-item label="简历内容">
        <a-input v-model:value="selectedResume.resumeContent" />
      </a-form-item>
      <a-form-item label="简历文件">
        <a-upload
          :before-upload="handleBeforeUpload"
          :customRequest="handleCustomRequest"
          :file-list="fileList"
          :remove="handleRemoveFile"
        >
          <a-button>
            <upload-outlined></upload-outlined>
            上传文件
          </a-button>
        </a-upload>
        <div v-if="selectedResume.resumeFileUrl">
          已上传文件: {{ selectedResume.resumeFileUrl.split('/').pop() }}
        </div>
      </a-form-item>
      <a-form-item label="默认简历">
        <a-select v-model:value="selectedResume.isDefault" style="width: 100%">
          <a-select-option :value="1">是</a-select-option>
          <a-select-option :value="0">否</a-select-option>
        </a-select>
      </a-form-item>

    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
import { h } from 'vue';
import { UploadOutlined } from '@ant-design/icons-vue';

/* eslint-disable */
// 类型定义
interface Resume {
  resumeId?: number;
  userId: number;
  resumeTitle: string;
  resumeContent: string;
  resumeFileUrl: string;
  isDefault: number;
  createdAt?: string;
}

// 用户列表
const users = ref([]);

// 获取用户列表
const fetchUsers = async () => {
  try {
    const res = await axios.get('/users/list', {
      params: {
        page: 1,
        size: 100 // 假设最多100个用户
      }
    });
    if (res.data.code === 200) {
      users.value = res.data.data.list;
    } else {
      message.error('加载用户列表失败');
    }
  } catch (err) {
    console.error('请求失败:', err);
    message.error('网络异常，请重试');
  }
};

// 根据用户ID获取用户名
const getUserDisplayName = (userId: number) => {
  const user = users.value.find(u => u.userId === userId);
  return user ? user.username : '未知用户';
};

// 初始化时加载用户列表
onMounted(async () => {
  await fetchUsers();
  await fetchResumes();
});

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
});

// 简历列表
const resumes = ref<Resume[]>([]);
const isLoading = ref(true);

// 搜索关键词
const searchKeyword = ref('');

// 弹窗控制
const open = ref(false);
const confirmLoading = ref(false);
const formRef = ref();

// 当前编辑项
const selectedResume = ref<Resume>({
  userId: 0, // 示例用户ID，
  resumeTitle: '',
  resumeContent: '',
  resumeFileUrl: '',
  isDefault: 0
});

// 列定义
const columns = [
  {
    title: '简历ID',
    dataIndex: 'resumeId'
  },
  {
    title: '用户名',
    dataIndex: 'userId'
  },
  {
    title: '标题',
    dataIndex: 'resumeTitle'
  },
  {
    title: '内容',
    dataIndex: 'resumeContent'
  },
  {
    title: '文件地址',
    dataIndex: 'resumeFileUrl',
    customRender: ({ text }: { text: string }) => {
      if (!text) return '';
      const filename = text.split('/').pop(); // 防止中文出错
      console.log("filename"+filename);
      return h('a', {

          href: `http://localhost:8080/upload/${filename}`,
          target: '_blank',
          rel: 'noopener noreferrer'

      }, filename);
    }
  }
,
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    customRender: ({ text }: { text: string }) => formatDate(text)
  },
  {
    title: '默认简历',
    dataIndex: 'isDefault',
    customRender: ({ text }: { text: number }) => (text === 1 ? '是' : '否')
  },
  {
    title: '操作',
    dataIndex: 'action'
  }
];


// 获取简历列表
const fetchResumes = async () => {
  try {
    isLoading.value = true;
    const res = await axios.get('/resumes/list', {
      params: {
        page: pagination.value.current,
        size: pagination.value.pageSize
      }
    });
    isLoading.value = false;

    if (res.data.code === 200) {
      pagination.value.total = res.data.data.total;
      resumes.value = res.data.data.list;
    } else {
      message.error('加载简历失败');
    }
  } catch (err) {
    console.error('请求失败:', err);
    message.error('网络异常，请重试');
    isLoading.value = false;
  }
};

// 新增/编辑提交
const handleOk = () => {
  confirmLoading.value = true;
  setTimeout(() => {
    open.value = false;
    confirmLoading.value = false;
  }, 500);

  // 创建一个新的对象，用于发送请求
  const requestData = { ...selectedResume.value };

  // 如果有文件路径，只发送文件名
  if (requestData.resumeFileUrl) {
    requestData.resumeFileUrl = getFileName(requestData.resumeFileUrl);
  }

  axios.post('/resumes/update', requestData).then(res => {
    if (res.data.code === 200) {
      fetchResumes();
      message.success('保存成功');
    } else {
      message.error('保存失败');
    }
  }).catch(err => {
    console.error('请求失败:', err);
    message.error('保存失败，请重试');
  });
};

// 删除简历
const deleteResume = (record: Resume) => {
  axios.post('/resumes/delete', { resumeId: record.resumeId }).then(() => {
    fetchResumes();
    message.success('删除成功');
  }).catch(() => {
    message.error('删除失败');
  });
};

// 模态框显示
const showModal = (record?: Resume) => {
  if (record) {
    selectedResume.value = { ...record };
  } else {
    selectedResume.value = {
      userId: 1,
      resumeTitle: '',
      resumeContent: '',
      resumeFileUrl: '',
      isDefault: 0
    };
  }
  open.value = true;
};

// 分页切换
const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  fetchResumes();
};

// 搜索逻辑
const handleSearch = () => {
  axios.post('/resumes/query', {
    resumeTitle: searchKeyword.value,
    username: searchKeyword.value
  }).then(res => {
    if (res.data.code === 200) {
      resumes.value = res.data.data;
      pagination.value.total = res.data.data.length;
    } else {
      message.error('搜索失败');
    }
  }).catch(err => {
    console.error('搜索失败:', err);
    message.error('搜索失败，请重试');
  });
};

// 格式化日期
const formatDate = (dateStr: string) => {
  return dateStr ? dayjs(dateStr).format('YYYY-MM-DD HH:mm:ss') : '';
};

// 新增方法：获取文件名
const getFileName = (filePath: string) => {
  return filePath.split('/').pop() || '';
};

// 响应式数据
const selectedFile = ref(null);
const uploadStatus = ref('');
const fileList = ref([]);

// 上传前的检查
const handleBeforeUpload = (file) => {
  const isJpgOrPng = file.type === 'application/pdf' || file.type === 'application/msword' || file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
  if (!isJpgOrPng) {
    message.error('只能上传PDF、Word文档!');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('文件大小不能超过2MB!');
    return false;
  }
  return true;
};

// 自定义上传请求
const handleCustomRequest = async (options) => {
  const { file, onSuccess, onError } = options;
  const formData = new FormData();
  formData.append('file', file);
  try {
    const response = await axios.post('http://localhost:8080/file/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    onSuccess(response.data);
    uploadStatus.value = response.data.message || '上传成功';
    message.success(uploadStatus.value);
    selectedResume.value.resumeFileUrl = file.name;
    fileList.value = [{ uid: file.uid, name: file.name }];
  } catch (error) {
    onError(error);
    uploadStatus.value = '上传失败: ' + error.message;
    message.error(uploadStatus.value);
  }
};

// 移除文件
const handleRemoveFile = (file) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
  selectedResume.value.resumeFileUrl = '';
};

</script>

<style scoped>
.ant-form-item {
  width: 100%;
}

/* 新增样式：确保表单项内容区域左对齐 */
.ant-form-item-control {
  flex: 1;
}
</style>